package com.vcredit.creditcat.time;

import com.vcredit.creditcat.manager.SpeedloanManager;
import com.vcredit.creditcat.model.ProcessSpecialCust;
import com.vcredit.creditcat.redis.RedisServiceExt;
import com.vcredit.creditcat.util.ConcurrentDateUtil;
import com.vcredit.creditcat.util.Utility;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 快速贷款的定时任务（手动）
 */
@JobHander(value="speedLoanHand")
@Component
public class SpeedloanHandTime extends IJobHandler {

	private static Logger LOG = LoggerFactory.getLogger(SpeedloanHandTime.class);

	@Autowired
	private SpeedloanManager speedloanManager;

	@Autowired
	private ThreadPoolTaskExecutor threadPoolTaskExecutor;

	@Autowired
	private RedisServiceExt redisServiceExt;

	@Override
	public ReturnT<String> execute(String... strings) throws Exception {
		if(strings.length<=0){
			return ReturnT.FAIL;
		}
		Object status = redisServiceExt.get("speedloan:status"+strings[0]);
		if (status != null) {
			return ReturnT.SUCCESS;
		}
		redisServiceExt.put("speedloan:status"+strings[0], "doing", 360000);
		LOG.info("快速贷款认证定时任务（手动）执行了.......ID:"+strings[0]+"===" + ConcurrentDateUtil.formatDateTime(new Date()));

		//多线程
		List<ProcessSpecialCust> handleList = new ArrayList<ProcessSpecialCust>();
		try {
			handleList = speedloanManager.findBySpecialId(Long.parseLong(strings[0]));
		} catch (Exception e) {
			LOG.error("快速贷款认证定时任务查询异常===ID:"+strings[0], e);
			e.printStackTrace();
		}
		if (Utility.isNullOrEmpty(handleList)) {
			redisServiceExt.del("speedloan:status"+strings[0]);
			return ReturnT.SUCCESS;
		}

		LOG.info("快速贷款认证定时任务处理数量========ID:"+strings[0]+"==="+ handleList.size());
		for (ProcessSpecialCust processSpecialCust : handleList) {
			try {
				speedloanManager.handleSpeedloan(processSpecialCust);
			} catch (Exception e) {
				LOG.error("快速贷款认证定时任务处理异常===ID:"+strings[0], e);
			}
		}
		redisServiceExt.del("speedloan:status"+strings[0]);

		return ReturnT.SUCCESS;
	}
}
